<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\controller\v1\setting\storage;

use kitego\base\BaseController;
use kitego\enum\StorageEnum;
use kitego\services\setting\StorageService;
use think\App;
use think\response\Json;

class StorageController extends BaseController
{
    public array $safeAction = ['list'];

    private StorageService $service;

    public function __construct(App $app, StorageService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 存储列表页面结构
     */
    public function schema(): Json
    {
        $jsonFilePath = __DIR__ . '/' . 'storageSchema.json';
        $jsonContent = file_get_contents($jsonFilePath);

        if ($jsonContent === false) exception('文件读取失败');

        return amis_success($jsonContent);
    }

    /**
     * 存储列表数据
     */
    public function list()
    {
        $where[] = ['is_delete', '=', 0];

        if (!empty($this->params['type'])) $where[] = ['type', '=', $this->params['type']];

        $storageQuery = $this->service->page($where);

        return amis_success(parse_amis_page($storageQuery));
    }

    /**
     * 新增存储类型
     */
    public function add()
    {
        if (
            empty($this->params['type']) ||
            !in_array($this->params['type'], [StorageEnum::QCLOUD, StorageEnum::ALIYUN, StorageEnum::QINIU])
        ) exception('存储类型错误');

        if (!isset($this->params['active']) || !in_array($this->params['active'], [1, 0])) exception('开启状态错误');

        if (!empty($this->params['domain']) && !check_url($this->params['domain'])) exception('domain格式错误');

        $res = \think\facade\Db::transaction(function () {
            // 只能开启一个存储方式
            if ($this->params['active'] == 1) {
                $this->service->update([['active', '=', 1]], ['active' => 0]);
            }

            $data = [
                'type' => $this->params['type'],
                'active' => $this->params['active'],
                'is_delete' => 0,
                'create_time' => now()
            ];

            $data = array_merge($this->handleData(), $data);

            return $this->service->save($data);
        });

        return amis_success($res);
    }

    /**
     * 编辑存储类型
     */
    public function edit()
    {
        $id = $this->params['id'] ?? 0;
        if (empty($id)) exception('id错误');

        if (!empty($this->params['domain']) && !check_url($this->params['domain'])) exception('domain格式错误');

        $res = \think\facade\Db::transaction(function () use ($id) {
            // 只能开启一个存储方式
            if ($this->params['active'] == 1) {
                $this->service->update([['active', '=', 1]], ['active' => 0]);
            }

            $data = [
                'type' => $this->params['type'],
                'active' => $this->params['active'],
                'is_delete' => 0,
                'update_time' => now()
            ];

            $data = array_merge($this->handleData(), $data);

            return $this->service->update($id, $data);
        });

        return amis_success($res);
    }

    /**
     * 删除存储方式
     */
    public function delete()
    {
        $id = $this->params['id'] ?? 0;
        if (empty($id)) exception('id错误');

        // 保持始终开启一个存储方式
        $activeQuery = $this->service->find([['active', '=', 1], ['id', '!=', $id]]);
        if (!$activeQuery && $this->params['active'] == 1) exception('保持始终开启一个存储方式');

        $data = [
            'is_delete' => 1,
            'delete_time' => now()
        ];

        $res = $this->service->update($id, $data);

        return amis_success($res);
    }

    /**
     * 批量删除存储类型
     */
    public function bulkDelete()
    {
        $ids = $this->params['ids'];
        if (empty($ids)) exception('id勾选错误');

        $ids = explode(',', $ids);
        $data = [
            'is_delete' => 1,
            'delete_time' => now()
        ];

        $activeQuery = $this->service->find([['id', 'in', $ids], ['active', '=', 1]]);
        if ($activeQuery) exception('已开启状态不可删除');

        $res = $this->service->update([['id', 'in', $ids]], $data);

        return amis_success($res);
    }

    /**
     * 新增|编辑共有数据处理
     */
    public function handleData()
    {
        switch ($this->params['type']) {
            case StorageEnum::QINIU:
                $dataTemp = [
                    'domain' => $this->params['domain'],
                    'qiniu_access_key' => $this->params['qiniuAccessKey'],
                    'qiniu_secret_key' => $this->params['qiniuSecretKey'],
                    'qiniu_bucket' => $this->params['qiniuBucket'],
                ];
                break;
            case StorageEnum::ALIYUN:
                $dataTemp = [
                    'domain' => $this->params['domain'],
                    'aliyun_access_key_id' => $this->params['aliyunAccessKeyId'],
                    'aliyun_access_key_secret' => $this->params['aliyunAccessKeySecret'],
                    'aliyun_endpoint' => $this->params['aliyunEndpoint'],
                    'aliyun_bucket' => $this->params['aliyunBucket'],
                ];
                break;
            case StorageEnum::QCLOUD:
                $dataTemp = [
                    'domain' => $this->params['domain'],
                    'qcloud_app_id' => $this->params['qcloudAppId'],
                    'qcloud_secret_id' => $this->params['qcloudSecretId'],
                    'qcloud_secret_key' => $this->params['qcloudSecretKey'],
                    'qcloud_bucket' => $this->params['qcloudBucket'],
                    'qcloud_region' => $this->params['qcloudRegion'],
                ];
                break;
        }

        return $dataTemp ?? [];
    }
}